package com.jsptags.navigation.pager;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.TagSupport;

@SuppressWarnings("serial")
public abstract class PagerTagSupport extends TagSupport {

	protected PagerTag pagerTag;
	static Class<PagerTag> clazz; /* synthetic field */

	protected final void restoreAttribute(String s, Object obj) {
		if (obj != null)
			pageContext.setAttribute(s, obj);
		else
			pageContext.removeAttribute(s);
	}

	private final PagerTag findRequestPagerTag(String s) {
		Object obj = pageContext.getRequest().getAttribute(s);
		if (obj instanceof PagerTag)
			return (PagerTag) obj;
		else
			return null;
	}

	public int doStartTag() throws JspException {
		if (id != null) {
			pagerTag = findRequestPagerTag(id);
			if (pagerTag == null)
				throw new JspTagException("pager tag with id of \"" + id
						+ "\" not found.");
		} else {
			pagerTag = (PagerTag) findAncestorWithClass(this, clazz == null
					&& (clazz = class$("com.jsptags.navigation.pager.PagerTag",
							false)) == null ? clazz : clazz);
			if (pagerTag == null) {
				pagerTag = findRequestPagerTag("pager");
				if (pagerTag == null)
					throw new JspTagException(
							"not nested within a pager tag and no pager tag found at request scope.");
			}
		}
		return 1;
	}

	public int doEndTag() throws JspException {
		pagerTag = null;
		return 6;
	}

	public void release() {
		pagerTag = null;
		super.release();
	}

	@SuppressWarnings("unchecked")
	static Class class$(String s, boolean flag) {
		try {
			Class claz = Class.forName(s);
			if (flag) {
				return null;
			} else {
				return claz;
			}
		} catch (ClassNotFoundException e) {
			throw new NoClassDefFoundError(e.getMessage());
		}

	}

	public PagerTagSupport() {
		pagerTag = null;
	}
}
